package com.oracle.coherence.patterns.security.test.starter;

import com.oracle.coherence.patterns.security.SystemPropertyLoader;
import org.apache.log4j.Logger;

public class CoherenceClusterStarter {
    private static final Logger logger = Logger.getLogger(CoherenceClusterStarter.class);
    private static CoherenceClusterStarter sInstance;

    /**
     * If you want to start up the cluster separately
     */
    public static void main(String[] args) throws Throwable {
        CoherenceClusterStarter.getInstance();
        Object lock = new Object();
        synchronized (lock) {
            lock.wait();
        }
    }

    /**
     * Makes sure the Cluster has started.
     */
    public synchronized static CoherenceClusterStarter getInstance() throws Throwable {
        if(sInstance == null) { sInstance = new CoherenceClusterStarter(); }
        return sInstance;
    }

    private CoherenceClusterStarter() throws Throwable {
        logger.info("Starting Coherence Cluster");
        // Load up the the storage nodes.
        SystemPropertyLoader.loadEnvironment("storage");
        int storageCount = SystemPropertyLoader.getRequiredInteger("coherence.incubator.storageCount");

        String mainClass = "com.oracle.coherence.patterns.security.test.starter.CoherenceSandboxStarter";
        mainClass = System.getProperty("coherence.incubator.mainclass", mainClass);

        logger.info("Starting Storage nodes : " + storageCount);
        for(int i=0;i<storageCount;i++) {
            logger.debug("Starting Storage : " + i);
            new SandboxRunner(mainClass);
        }

        // Load up the proxy nodes.
        SystemPropertyLoader.loadEnvironment("extends");
        int proxyCount = SystemPropertyLoader.getRequiredInteger("coherence.incubator.proxyCount");
        logger.info("Starting Proxy nodes : " + proxyCount);
        for(int i=0;i<proxyCount;i++) {
            logger.debug("Starting Proxy : " + i);
            new SandboxRunner(mainClass);
        }
        logger.info("Started cluster");

    }
}
